<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  
  <title>PHP实现无限级分类 -- path标识 | 程序小工  | Just do it!</title>
  <meta name="description" content="遇见更好的自己~" />
  <meta name="keywords" content="" />
  <meta name="HandheldFriendly" content="True" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <link rel="shortcut icon" href="/">
  <link rel="alternate" href="/atom.xml" title="程序小工  | Just do it!">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="在实际项目中经常要用到无限级分类，如多级分类、导航表等。PHP 实现无限级分类通常有两种实现方式，一种是利用path字段（pid+id）标识当前层级；另一种是利用递归循环pid的方式。此处介绍前种方式。">
<meta name="keywords" content="无限级分类">
<meta property="og:type" content="article">
<meta property="og:title" content="PHP实现无限级分类 -- path标识">
<meta property="og:url" content="http://blog.i2arch.tech/2018/05/16/php-无限级分类/index.html">
<meta property="og:site_name" content="程序小工  | Just do it!">
<meta property="og:description" content="在实际项目中经常要用到无限级分类，如多级分类、导航表等。PHP 实现无限级分类通常有两种实现方式，一种是利用path字段（pid+id）标识当前层级；另一种是利用递归循环pid的方式。此处介绍前种方式。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-08-14T07:59:24.559Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="PHP实现无限级分类 -- path标识">
<meta name="twitter:description" content="在实际项目中经常要用到无限级分类，如多级分类、导航表等。PHP 实现无限级分类通常有两种实现方式，一种是利用path字段（pid+id）标识当前层级；另一种是利用递归循环pid的方式。此处介绍前种方式。">
    
  <link href="https://fonts.googleapis.com/css?family=Inconsolata|Titillium+Web" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Roboto+Mono" rel="stylesheet">
  <link href='//cdn.bootcss.com/node-waves/0.7.5/waves.min.css' rel='stylesheet'>
  <link rel="stylesheet" href="/style.css">
  <script>
    function setLoadingBarProgress(num) {
      document.getElementById('loading-bar').style.width=num+"%";
    }
  </script>
</head>

<body>
  <div id="loading-bar-wrapper">
  <div id="loading-bar"></div>
</div>


  <script>setLoadingBarProgress(20)</script>
  <header class="l_header">
	<div class='wrapper'>
		<div class="nav-main container container--flex">
			<a class="logo flat-box" href='/' >
				程序小工  | Just do it!
			</a>
			<div class='menu'>
				<ul class='h-list'>
					
						<li>
							<a class='flat-box nav-home' href='/'>
								<i class='icon icon-list2'></i>
								首页
							</a>
						</li>
					
						<li>
							<a class='flat-box nav-archives' href='/archives'>
								<i class='icon icon-bookmark'></i>
								归档
							</a>
						</li>
					
						<li>
							<a class='flat-box nav-about' href='/about'>
								<i class='icon icon-user'></i>
								关于
							</a>
						</li>
					
				</ul>
				<div class='underline'></div>
			</div>
			
				<div class="m_search">
					<form name="searchform" class="form u-search-form">
						<input type="text" class="input u-search-input" placeholder="Search" />
						<span class="icon icon-search"></span>
					</form>
				</div>
			
			<ul class='switcher h-list'>
				
					<li class='s-search'><a href='javascript:void(0)'><span class="icon icon-search flat-box"></span></a></li>
				
				<li class='s-menu'><a href='javascript:void(0)'><span class="icon icon-menu flat-box"></span></a></li>
			</ul>
		</div>

		<div class='nav-sub container container--flex'>
			<a class="logo" class="flat-box" href='javascript:void(0)'>
				Word of Forks
			</a>

			<ul class='switcher h-list'>
				<li class='s-comment'><a href='javascript:void(0)'><span class="icon icon-chat_bubble_outline flat-box"></span></a></li>
				<li class='s-top'><a href='javascript:void(0)'><span class="icon icon-arrow_upward flat-box"></span></a></li>
				<li class='s-toc'><a href='javascript:void(0)'><span class="icon icon-format_list_numbered flat-box"></span></a></li>
			</ul>
		</div>
	</div>
</header>
<aside class="menu-phone">
	<nav>
		
			<a href="/" class="nav-home nav">
				首页
			</a>
		
			<a href="/archives" class="nav-archives nav">
				归档
			</a>
		
			<a href="/about" class="nav-about nav">
				关于
			</a>
		
	</nav>
</aside>

    <script>setLoadingBarProgress(40);</script>
  <div class="l_body">
    <div class='container clearfix'>
      <!-- 左侧内容 -->
      <div class='l_main'>
        <article id="post-php-无限级分类"
  class="post white-box article-type-post"
  itemscope itemprop="blogPost">
	<section class='meta'>

	<h2 class="title">
  	<a href="/2018/05/16/php-无限级分类/">
    	PHP实现无限级分类 -- path标识
    </a>
	</h2>

	<div class="pagenav">
		<time>
			2018-05-16
		</time>

		
    
    <div class='cats'>
        <i class="icon icon-bookmark"></i>
        <a href="/categories/PHP/">PHP</a>
    </div>


		
			<div class="pagetags">
				<i class="icon icon-price-tag" style="margin-right: 2px;"></i>
				
					<a href="/tags/无限级分类/" style="margin-left: 3px;">
						无限级分类
					</a>
				
			</div>
			
	</div>
	</section>

	
	<section class="toc-wrapper"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#php-实现无限级分类-path标识"><span class="toc-text"> PHP 实现无限级分类 – path标识</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-数据库设计"><span class="toc-text"> 1、数据库设计</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-php-代码实现"><span class="toc-text"> 2、PHP 代码实现</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-视图层显示"><span class="toc-text"> 3、视图层显示</span></a></li></ol></li></ol></section>
	

	<section class="article typo">
		<div class="article-entry" itemprop="articleBody">
				<span class="zhaiyao">[摘要]</span>
			<p>在实际项目中经常要用到无限级分类，如多级分类、导航表等。PHP 实现无限级分类通常有两种实现方式，一种是利用<code>path</code>字段（pid+id）标识当前层级；另一种是利用递归循环<code>pid</code>的方式。此处介绍前种方式。</p>
<a id="more"></a>
<h1 id="php-实现无限级分类-path标识"><a class="markdownIt-Anchor" href="#php-实现无限级分类-path标识"></a> PHP 实现无限级分类 – <code>path</code>标识</h1>
<h2 id="1-数据库设计"><a class="markdownIt-Anchor" href="#1-数据库设计"></a> 1、数据库设计</h2>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">--创建分类表</span></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> <span class="string">`b_category`</span>(</span><br><span class="line"><span class="string">`id`</span> <span class="built_in">int</span> primary <span class="keyword">key</span> <span class="keyword">not</span> <span class="literal">null</span> auto_increment,</span><br><span class="line"><span class="string">`cat_name`</span> <span class="built_in">varchar</span>(<span class="number">20</span>) <span class="keyword">not</span> <span class="literal">null</span> <span class="keyword">default</span> <span class="string">''</span>,</span><br><span class="line"><span class="string">`cat_description`</span> <span class="built_in">text</span> <span class="keyword">default</span> <span class="string">''</span>,</span><br><span class="line"><span class="string">`level`</span> <span class="built_in">int</span> <span class="keyword">not</span> <span class="literal">null</span> <span class="keyword">default</span> <span class="number">0</span> <span class="keyword">comment</span> <span class="string">'等级'</span>,</span><br><span class="line"><span class="string">`pid`</span> <span class="built_in">int</span> <span class="keyword">comment</span> <span class="string">'父级id'</span>,</span><br><span class="line"><span class="string">`path`</span> <span class="built_in">varchar</span>(<span class="number">10</span>) <span class="keyword">comment</span> <span class="string">'pid+,+id标识，用于无限级分类'</span></span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<h2 id="2-php-代码实现"><a class="markdownIt-Anchor" href="#2-php-代码实现"></a> 2、PHP 代码实现</h2>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">$data = $m-&gt;field(<span class="string">"*, concat(path,',',id) as paths "</span>)-&gt;order(<span class="string">'paths'</span>)-&gt;select();</span><br><span class="line"></span><br><span class="line"><span class="keyword">foreach</span>($data <span class="keyword">as</span> $k=&gt;$v )&#123;</span><br><span class="line">    $data[$k][<span class="string">'name'</span>] = str_repeat(<span class="string">"   "</span>, $v[<span class="string">'level'</span>]) . $v[<span class="string">'name'</span>];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="3-视图层显示"><a class="markdownIt-Anchor" href="#3-视图层显示"></a> 3、视图层显示</h2>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&lt;div class="row cl"&gt;</span><br><span class="line">  &lt;label class="dorm-label col-2"&gt;描述：&lt;/lable&gt;</span><br><span class="line">  &lt;div class="formControls col-5"&gt;</span><br><span class="line">      &lt;span class="select-box"&gt;</span><br><span class="line">         &lt;select class="select" size="1" name="pid"&gt;</span><br><span class="line">            &lt;option value=<span class="string">"0"</span> selected&gt;顶级分类&lt;/option&gt;</span><br><span class="line">            &#123;<span class="keyword">foreach</span> $data <span class="keyword">as</span> $item&#125;</span><br><span class="line">               &lt;option value=<span class="string">"&#123;$item.id&#125;"</span>&gt;&#123;$item.name&#125;&lt;/option&gt;</span><br><span class="line">            &#123;/<span class="keyword">foreach</span>&#125;</span><br><span class="line">         &lt;/select&gt;</span><br><span class="line">      &lt;/span&gt;</span><br><span class="line">   &lt;/div&gt;</span><br><span class="line">  &lt;/div&gt;</span><br></pre></td></tr></table></figure>

		</div>

		
			<div class="art-item-footer">
					
						<span class="art-item-left"><i class="icon icon-chevron-thin-left"></i> <a href="/2018/06/05/mysql-compare/" rel="prev" title="MySQL数据库常见名词对比">
							MySQL数据库常见名词对比
						</a>上一篇文章</span>
					
					
						<span class="art-item-right">下一篇文章：<a href="/2018/05/15/movie-wxsnr/" rel="next"  title="电影《闻香识女人》">
							电影《闻香识女人》
						</a><i class="icon icon-chevron-thin-right"></i></span>
					
			</div>
		

		
			

    <div class="recommended_posts">
        <h3>推荐文章</h3>
        <ul>
            
                <li><a href="http://blog.i2arch.tech/2018/06/20/summary-monthly2/">【总结】两个月的工作任务总结</a></li>
            
                <li><a href="http://blog.i2arch.tech/2018/06/05/mysql-compare/">MySQL数据库常见名词对比</a></li>
            
                <li><a href="http://blog.i2arch.tech/2018/05/15/movie-wxsnr/">电影《闻香识女人》</a></li>
            
                <li><a href="http://blog.i2arch.tech/2018/05/14/sphinx-php-windows/">windows7使用Sphinx+PHP+MySQL详细介绍</a></li>
            
        </ul>
    </div>


		
	</section>

	

</article>
<script>
	window.subData = {
		title: 'PHP实现无限级分类 -- path标识',
		tools: true
	}
</script>

      </div>

      <!-- 右侧边栏组件 -->
      <aside class='l_side'>
        
      </aside>

      <div class="gotop">
          
    <a href='javascript:void(0)'>
        <i class="icon icon-arrow_upward flat-box">
        </i>
    </a>

      </div>
      <script>setLoadingBarProgress(60);</script>
    </div>
  </div>
  <footer id="footer" class="clearfix">

	<div class="social-wrapper">
  	
      
        <a href="https://github.com/zqunor" class="social github"
          target="_blank" rel="external">
          <span class="icon icon-github"></span>
        </a>
      
        <a href="https://www.cnblogs.com/zqunor" class="social zhihu"
          target="_blank" rel="external">
          <span class="icon icon-zhihu"></span>
        </a>
      
        <a href="/atom.xml" class="social rss"
          target="_blank" rel="external">
          <span class="icon icon-rss"></span>
        </a>
      
    
  </div>
  <div>Theme <a href='https://github.com/stkevintan/hexo-theme-material-flow' class="codename">MaterialFlow</a>  Powered by<a href="https://blog.i2arch.tech/" target="_blank">程序小工</a>.</div>

</footer>

  <script>setLoadingBarProgress(80);</script>
  

    <script src="//apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src='//cdn.bootcss.com/node-waves/0.7.5/waves.min.js'></script>
    <script src="//cdn.bootcss.com/scrollReveal.js/3.3.2/scrollreveal.min.js"></script>
    <script src="/js/jquery.fitvids.js"></script>
      <script>
        var GOOGLE_CUSTOM_SEARCH_API_KEY = "";
        var GOOGLE_CUSTOM_SEARCH_ENGINE_ID = "";
        var ALGOLIA_API_KEY = "";
        var ALGOLIA_APP_ID = "";
        var ALGOLIA_INDEX_NAME = "";
        var AZURE_SERVICE_NAME = "";
        var AZURE_INDEX_NAME = "";
        var AZURE_QUERY_KEY = "";
        var BAIDU_API_ID = "fca5b83cf69f752ddc96a61ef64a3659";
        var SEARCH_SERVICE = "hexo";
        var ROOT = "/" || "/";
        if (!ROOT.endsWith('/')) ROOT += '/';
      </script>
      <script src="/js/search.js"></script>
        <script src="/js/app.js"></script>
  <script>setLoadingBarProgress(100);</script>
</body>
</html>
